package com.hboxs.asl.qcloudLVB.controller.asl;

import com.hboxs.asl.*;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.qcloudLVB.Conf;
import com.hboxs.asl.qcloudLVB.entity.Live;
import com.hboxs.asl.qcloudLVB.service.LiveService;
import com.hboxs.asl.service.*;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by xxx on 10/12/2016.
 * <p>
 * Controller -- 前端接口
 * <p>
 */
@Controller(value = "aslLiveController")
@RequestMapping(value = "/weChat/live")
public final class LiveController extends BaseController {

    //直播流开关状态( 0:关闭； 1:开启 )
    private static final int LIVE_ONLINE = 1;
    private static final int LIVE_OFFLINE = 0;

    protected Logger logger = Logger.getLogger(getClass());

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "liveServiceImpl")
    private LiveService liveService;
    @Resource(name = "productServiceImpl")
    private ProductService productService;
    @Resource(name = "liveGiftServiceImpl")
    private LiveGiftService liveGiftService;
    @Resource(name = "courseServiceImpl")
    private CourseService courseService;
    @Resource(name = "courseTradeServiceImpl")
    private CourseTradeService courseTradeService;

    /**
     * 课程(status==live)界面(用户端)l
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Long id, ModelMap model) {

        Member member = memberService.getCurrent();

        //判断当前用户是否报名课程
        boolean apply = false;
        CourseTrade courseTrade = courseTradeService.courseTradeCount(CourseTrade.PaymentStatus.paid, member, id);
        if (courseTrade != null) {
            apply = true;
        }

        Course course = courseService.find(id);

        if(course==null){
            return FZF;
        }

        model.addAttribute("course" , course);
        model.addAttribute("apply", apply);
        model.addAttribute("download_url" , Constant.DOWNLOAD_APP);

        return "/yijing/live/index";
    }


    /**
     * 课程(status==live)界面(用户端)l
     */
    @RequestMapping(value = "/video", method = RequestMethod.GET)
    public String video(String url, ModelMap model) {

        model.addAttribute("url" , url);

        return "/yijing/live/video";
    }

    /**
     * 直播内容商品列表
     *
     * @param id 直播id
     */
    @RequestMapping(value = "/products", method = RequestMethod.POST)
    public
    @ResponseBody
    Object products(Long id) {

        Live live = liveService.find(id);

        if (live == null) {
            return JsonMessage.error("直播不存在");
        }

        if (!live.getLiveStatus().equals(Live.LiveStatus.live) || live.getAnchor() == null) {
            return JsonMessage.error("数据错误");
        }

        Set<Product> products = live.getProducts();

        return JsonMessage.success(
                JsonMessage.optimiseObj(
                        products, "id", "name", "price", "promotionPrice", "sales", "image"
                )
        );
    }


    /**
     * 用户端:直播内容
     *
     * @param id 直播id
     * @return json
     */
    @RequestMapping(value = "/content", method = RequestMethod.GET)
    public Object content(Long id, ModelMap model) {

        //观众
        Member member = memberService.getCurrent();

        Live live = liveService.find(id);

        if (live == null) {
            return JsonMessage.error("直播不存在");
        }

        if (!Live.LiveStatus.live.equals(live.getLiveStatus()) || live.getAnchor() == null) {
            return JsonMessage.error("直播状态异常");
        }

        //获取播放地址
        Map<String, String> map = liveService.getPlayUrl(Conf.BIZID, live.getId().toString());
        //1.如果用户是在登录情况下访问直播内容,则需进行观看人数的增加,
        if (member != null) {
            liveService.changeCount(live.getAnchor(), member, 0, 0, 0, null);
        }

        model.addAttribute("url", map.get("m3u8"));
        model.addAttribute("live", live);


        return "/yijing/live/content";
    }


    /**
     * 用户端:直播内容
     *
     * @param id 直播id
     * @return json
     */
    @RequestMapping(value = "/contentSDK", method = RequestMethod.GET)
    public String contentSDK(Long id, ModelMap model) {

        //观众
        Member member = memberService.getCurrent();

        Live live = liveService.find(id);
        if(live.getCourse().getCharge() || live.getCourse().getEncrypt()){
            return FZF;
        }

        if (live == null) {
            return FZF;
        }

        if (!Live.LiveStatus.live.equals(live.getLiveStatus()) || live.getAnchor() == null) {
            return FZF;
        }


        //获取播放地址
        Map<String, String> map = liveService.getPlayUrl(Conf.BIZID, live.getId().toString());

        //1.如果用户是在登录情况下访问直播内容,则需进行观看人数的增加,
        if (member != null) {
            liveService.changeCount(live.getAnchor(), member, 0, 0, 0, null);
        }

        model.addAttribute("member" , member);
        model.addAttribute("url", map.get("m3u8"));
        model.addAttribute("live", live);

        return "/yijing/live/contentSDK";
    }


    /**
     * 微信端 ajax获取 直播数据包
     *
     * @param id 直播id
     * @return json
     */
    @RequestMapping(value = "/core_data", method = RequestMethod.POST)
    public
    @ResponseBody
    Object coreData(Long id) {
        //观众
        Member member = memberService.getCurrent();

        Live live = liveService.find(id);

        if (live == null) {
            return JsonMessage.error("直播不存在");
        }
        if (!Live.LiveStatus.live.equals(live.getLiveStatus()) || live.getAnchor() == null) {
            return JsonMessage.error("直播状态异常");
        }
        //获取播放地址
        Map<String, String> map = liveService.getPlayUrl(Conf.BIZID, live.getId().toString());
        //1.如果用户是在登录情况下访问直播内容,则需进行观看人数的增加,
        if (member != null) {
            liveService.changeCount(live.getAnchor(), member, 0, 0, 0, null);
        }

        Member anchor = live.getAnchor();

        // 直播：0 ，录播：1
        Integer type = 0;

        // 离线：0 ，在线：1
        Integer status = 0;
        if(Live.LiveStatus.live == live.getLiveStatus()){
            status = 1;
        }
        return JsonMessage.success(

                "anchor", JsonMessage.optimiseObj(anchor, "id", "username", "name", "avator")

                , "live", JsonMessage.optimiseObj(live, "groupid", "watchCount", "hisWatchCount", "admireCount", "cover")

                , "type", type

                , "status", status

                , "mUrl", map.get("m3u8")

                , "flv" , map.get("flv")

                );


    }


    /**
     * 主播信息
     */
    @RequestMapping(value = "/anchor_info", method = RequestMethod.GET)
    public
    @ResponseBody
    Object anchorInfo(Long id) {
        Live live = liveService.find(id);
        if (live == null) return JsonMessage.error("直播不存在");
        Member anchor = live.getAnchor();
        return JsonMessage.success("anchor", JsonMessage.optimiseObj(anchor, "id", "username", "name", "avator"));
    }

    /**
     * 关闭直播
     *
     * @param liveId 直播liveId
     * @return json
     */
    @RequestMapping(value = "/close", method = RequestMethod.POST)
    public
    @ResponseBody
    Object close(Long liveId) {
        Live live = liveService.find(liveId);
        if (live == null) {
            return JsonMessage.error("直播不存在");
        }
        Member anchor = live.getAnchor();

        if (!Live.LiveStatus.live.equals(live.getLiveStatus()) || anchor == null) {
            return JsonMessage.error("直播状态异常");
        }

        Member member = memberService.getCurrent();

        //主播主动关闭直播
        if (anchor.equals(member)) {
            Boolean ret = liveService.changeStatus(LIVE_OFFLINE, live.getId());
            if (!ret) {
                return JsonMessage.UNKNOWN_ERROR;
            }
        }

        //登陆用户关闭直播
        if (member != null && !anchor.equals(member)) {
            liveService.changeCount(live.getAnchor(), memberService.getCurrentByToken(), 0, 1, 0, null);
        }

        return JsonMessage.success();
    }

    /**
     * 修改流状态
     *
     * @return code
     */
    @RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
    public
    @ResponseBody
    Object changeStatus(int status, Long liveId) {
        Live live = liveService.find(liveId);
        if (live == null) {
            return JsonMessage.error("直播不存在");
        }
        if (live.getLiveStatus() != null && (Live.LiveStatus.finished.equals(live.getLiveStatus()) || Live.LiveStatus.forbidden.equals(live.getLiveStatus()))) {
            return JsonMessage.error("直播已结束");
        }

        Boolean ret = liveService.changeStatus(status, liveId);

        return ret ? JsonMessage.success() : JsonMessage.error("修改状态失败");

    }

    /**
     * 获取直播状态
     *
     * @param liveId 直播id
     * @return json
     */
    @RequestMapping(value = "/getLiveStatus", method = RequestMethod.POST)
    public
    @ResponseBody
    Object getLiveStatus(Long liveId) {

        Live live = liveService.find(liveId);

        return live == null ? JsonMessage.error("直播不存在") : JsonMessage.success(live.getLiveStatus().toString());

    }

    /**
     * 直播前挑选商品展示
     */
    @RequestMapping(value = "/product_array", method = RequestMethod.POST)
    public
    @ResponseBody
    Object array(@RequestParam(value = "ids") Long[] ids) {

        if (ids == null) {
            return JsonMessage.error("ids数组不能为空");
        }
        List<Product> lists = productService.findList(ids);
        return JsonMessage.success(
                JsonMessage.optimiseObj(
                        lists, "name", "id", "price", "promotionPrice", "image", "sales"
                )
        );
    }

    /**
     * 拉取群成员列表 fetchGroupMemberList
     *
     * @param id       直播id
     * @param pageable 分页信息
     */
    @RequestMapping(value = "/fetchGroupMemberList", method = RequestMethod.POST)
    public
    @ResponseBody
    Object fetchGroupMemberList(Long id, Pageable pageable) {
        Live live = liveService.find(id);
        pageable.getFilters().add(Filter.eq("watchingLive", live));
        Page<Member> page = memberService.findPage(pageable);
        return JsonMessage.success(

                "watchCount", live.getWatchCount(),

                "groupid", live.getGroupid(),

                "page", JsonMessage.optimiseObj(
                        page, "pageNumber", "pageSize", "totalPages", "total", "content.id#name#avator#username"
                )
        );
    }

    /**
     * 所有礼物
     */
    @RequestMapping(value = "/allGift", method = RequestMethod.POST)
    public
    @ResponseBody
    Object allGift() {

        return JsonMessage.success(

                JsonMessage.optimiseObj(liveGiftService.findAll(), "id", "coin", "name","image")
        );
    }


}